const User = require('../../Mongoose/User')
const crypto = require('crypto')
class AuthController {
    constructor() {

    }
    async signin (ctx, next) {
        if (ctx.method == 'GET') {
            let user = ctx.state.user
            if (user) {
                await ctx.redirect('/')                
                return next()                
            }
            await ctx.render('auth/signin')
            return next()
        }

        let username =  ctx.request.body.username
        let password =  ctx.request.body.password
        
        let user = await User.findOne({username: username})
        if (user) {
            console.log(user)
            if (user.password == crypto.createHash('md5').update(password).digest('hex')) {
                delete user['password']
                ctx.session.user = JSON.stringify(user)
                await ctx.redirect('/')
            } else {
                ctx.throw('500', '密码错误')
            }
        } else {
            ctx.throw('500', '用户不存在')
        }
    }
    async signup (ctx, next) {
        if (ctx.method == 'GET') {
            await ctx.render('auth/signup')
            return next()
        }
        if (ctx.request.body.password != ctx.request.body.repassword) {
            ctx.throw('密码不一致')
        }
        let data = {
            username: ctx.request.body.username,
            password: ctx.request.body.password,
            phone: ctx.request.body.phone,
            email: ctx.request.body.email,
            city: ctx.request.body.city
        }
        let user = await User.create(data)
        if (user) {
            ctx.session.user = null
            ctx.session.user = JSON.stringify(user)           
            await ctx.redirect('/', {user: user})                  
        }
    }
    async signout (ctx, next) {
        if (ctx.session) {
            ctx.session = null
        }
        await ctx.redirect('/signin')
    }

}
module.exports = new AuthController()